package com.wh.sse.service.impl;

import com.wh.common.dao.NoticeMapper;
import com.wh.common.pojo.Notice;
import com.wh.sse.service.SseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 1
 * @since 2024-06-24 星期一 20:34:51
 */
@Service
public class SseServiceImpl implements SseService {
    @Autowired
    private NoticeMapper noticeMapper;

    private static Map<Long, SseEmitter> sseEmitterMap = new ConcurrentHashMap<>();


    /**
     * 创建链接
     *
     * @param userId
     * @return
     */
    @Override
    public SseEmitter connect(Long userId) {
        SseEmitter sseEmitter = new SseEmitter(0L);

        //TODO 查询公告数据库取出置顶的数据，放到data
        Notice notice = noticeMapper.selectTop();
        System.out.println(notice + "查询成功");
        //链接断开
        sseEmitter.onCompletion(() -> {
            sseEmitterMap.remove(userId);
        });

        //链接超时
        sseEmitter.onTimeout(() -> {
            sseEmitterMap.remove(userId);
        });

        //链接报错
        sseEmitter.onError((throwable) -> {
            sseEmitterMap.remove(userId);
        });
        sseEmitterMap.put(userId, sseEmitter);
        try {
            sseEmitter.send(notice);
            sseEmitter.complete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sseEmitter;
    }

    /**
     * 发送消息
     *
     * @param notice
     * @param userId
     */
    @Override
    public void sendMessage(Notice notice, Long userId) {
        if (sseEmitterMap.containsKey(userId)) {
            SseEmitter sseEmitter = sseEmitterMap.get(userId);
            try {
                String noticeText = notice.getNoticeText();
                sseEmitter.send(noticeText);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
